In the realm of Java programming, the concept of inheritance stands as a cornerstone of code architecture. Java, known for its robust Object-Oriented Programming (OOP) capabilities, empowers developers to create software that is both efficient and extensible through the use of inheritance. This fundamental principle allows one class, known as the subclass or derived class, to inherit attributes and methods from another class, known as the superclass or base class.
The significance of inheritance lies in its ability to promote code reuse, foster extensibility, and facilitate the construction of hierarchical class structures. In this comprehensive guide, we embark on a journey to explore the diverse facets of Java inheritance, including its various types, practical applications, and essential best practices. If you are interested in learning more Java you can go through Java Certification Courses that are listed on our portal.
Also Read:
Inheritance in Java is a mechanism that allows a class (referred to as the subclass or derived class) to inherit properties and behaviours from another class (known as the superclass or base class). This promotes code reuse, extensibility, and the creation of a hierarchical class structure. Inheritance is one of the four fundamental OOP (Object-Oriented Programming) principles, which also include encapsulation, abstraction, and polymorphism.
There are several inheritance in Java types, each with its unique characteristics:
Single Inheritance: In single inheritance in Java, a class inherits from a single superclass. Java enforces single inheritance to avoid ambiguity in method resolution. For example, a class representing a "Car" can inherit from a superclass "Vehicle."
Java Multiple Inheritance: Multiple inheritance in Java allows a class to inherit from more than one superclass. However, Java does not support this directly due to potential issues like the "diamond problem." Instead, it employs interfaces to achieve similar results.
Multilevel Inheritance: Multilevel inheritance in Java is a cascade of inheritance, where a class extends another class, which, in turn, extends another class. This creates a chain of inheritance. For instance, a class "SportsCar" extending "Car," which extends "Vehicle."
Hierarchical Inheritance: In hierarchical inheritance in Java, multiple classes inherit from a single base class. For example, classes like "Cat," "Dog," and "Horse" can inherit from a common superclass "Animal."
Hybrid Inheritance: Hybrid inheritance in Java is a combination of multiple inheritance and multilevel inheritance. It is achieved through a combination of superclass and interface-based inheritance.
Also Read:
Single inheritance is the simplest form of inheritance in Java. It allows a class to inherit properties and methods from a single superclass. For example, consider a class "Dog" inheriting characteristics from the superclass "Animal." The "Animal" class may contain attributes like "name" and methods like "eat" and "sleep," which are inherited by the "Dog" class. Here is a code example :
// Creating a base class
class Animal {
void eat() {
System.out.println("Animal is eating");
}
void sleep() {
System.out.println("Animal is sleeping");
}
}
// Derived class inheriting from Animal
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
public class SingleInheritanceExample {
public static void main(String[] args) {
// Create an instance of Dog
Dog dog = new Dog();
// Call methods from the base class (Animal)
dog.eat();
dog.sleep();
// Call method from the derived class (Dog)
dog.bark();
}
}
As mentioned earlier, Java supports multiple inheritance through interfaces. An interface defines a set of abstract methods that a class implementing the interface must provide concrete implementations for. Classes can implement multiple interfaces, effectively inheriting from multiple sources. For example, a class "Smartphone" may implement interfaces like "Phone" and "Camera," inheriting their methods and attributes. Below is the code example for this scenario.
// Define an interface for things that can make calls
interface Phone {
void makeCall(String number);
}
// Define an interface for things that can take photos
interface Camera {
void takePhoto();
}
// Define a class that represents a smartphone
class Smartphone implements Phone, Camera {
// Implementing makeCall method from the Phone interface
@Override
public void makeCall(String number) {
System.out.println("Calling " + number);
}
// Implementing takePhoto method from the Camera interface
@Override
public void takePhoto() {
System.out.println("Taking a photo");
}
}
// Main class to test the functionality
public class Main {
public static void main(String[] args) {
// Create a smartphone object
Smartphone myPhone = new Smartphone();
// Use the smartphone to make a call
myPhone.makeCall("123456789");
// Use the smartphone to take a photo
myPhone.takePhoto();
}
}
In multilevel inheritance in Java, a class derives from a superclass, and another class derives from it, forming a hierarchical structure. This type of inheritance promotes code organisation and the creation of specialised classes. For instance, consider a class "Professor" inheriting from "Person," and a class "Student" inheriting from "Professor." The "Student" class indirectly inherits attributes and methods from the "Person" class through the "Professor" class. Check the following code for the same.
// Base class Person
class Person {
String name;
// Constructor to initialize name
public Person(String name) {
this.name = name;
}
// Method to display name
public void display() {
System.out.println("Name: " + name);
}
}
// Derived class Professor inherits from Person
class Professor extends Person {
String subject;
// Constructor to initialize name and subject
public Professor(String name, String subject) {
super(name); // Call Person constructor
this.subject = subject;
}
// Method to display name and subject
@Override
public void display() {
super.display(); // Call Person display method
System.out.println("Teaches: " + subject);
}
}
// Another derived class Student inherits from Professor
class Student extends Professor {
int studentId;
// Constructor to initialize name, subject, and student ID
public Student(String name, String subject, int studentId) {
super(name, subject); // Call Professor constructor
this.studentId = studentId;
}
// Method to display name, subject, and student ID
@Override
public void display() {
super.display(); // Call Professor display method
System.out.println("Student ID: " + studentId);
}
}
// Main class to test the functionality
public class Main {
public static void main(String[] args) {
// Create a Student object
Student student = new Student("Nikhil", "Careers360", 123);
// Display student details
student.display();
}
}
Also Read:
Hierarchical inheritance allows multiple classes to inherit from a single base class. This is useful when different classes share common attributes and methods. For example, classes like "Cat," "Dog," and "Horse" can inherit from a common superclass "Animal," which may include properties like "name" and methods like "speak." The following code provides a practical example for this case.
// Base class
class Animal {
// Attribute to store the name of the animal
protected String name;
// Constructor to initialize the name
public Animal(String name) {
this.name = name;
}
// Method to be overridden by subclasses
public void speak() {
System.out.println("Animal makes a sound");
}
}
// Derived class Cat
class Cat extends Animal {
// Constructor to initialize the name, calling the superclass constructor
public Cat(String name) {
super(name);
}
// Override the speak method for Cat
@Override
public void speak() {
System.out.println(name + " says Meow");
}
}
// Derived class Dog
class Dog extends Animal {
// Constructor to initialize the name, calling the superclass constructor
public Dog(String name) {
super(name);
}
// Override the speak method for Dog
@Override
public void speak() {
System.out.println(name + " says Woof");
}
}
// Main class to test hierarchical inheritance
public class Main {
public static void main(String[] args) {
// Creating instances of Cat and Dog
Cat cat = new Cat("Cat");
Dog dog = new Dog("Dog");
// Calling the speak method for each instance
cat.speak(); // Output: Whiskers says Meow
dog.speak(); // Output: Buddy says Woof
}
}
Hybrid inheritance combines multiple and multilevel inheritance to create a complex class hierarchy. This type of inheritance is achieved by incorporating interfaces along with class-based inheritance. For example, a class "Guitar" may inherit from a superclass "MusicalInstrument" and implement interfaces like "StringedInstrument" and "AcousticInstrument." Here is the code example:
// Interface for Stringed Instruments
interface Stringed_Instrument {
void playStringSound();
}
// Interface for Acoustic Instruments
interface Acoustic_Instrument {
void playAcousticSound();
}
// Base class for Musical Instruments
class Musical_Instrument {
protected String name;
public Musical_Instrument(String name) {
this.name = name;
}
public void play() {
System.out.println(name + " is playing");
}
}
// Derived class Guitar implementing both interfaces
class Guitar extends Musical_Instrument implements Stringed_Instrument, Acoustic_Instrument {
public Guitar(String name) {
super(name);
}
// Implementing method from StringedInstrument interface
@Override
public void playStringSound() {
System.out.println("Guitar strums strings");
}
// Implementing method from AcousticInstrument interface
@Override
public void playAcousticSound() {
System.out.println("Guitar produces acoustic sound");
}
}
// Main class to test hybrid inheritance
public class Main {
public static void main(String[] args) {
// Creating an instance of Guitar
Guitar guitar = new Guitar("Acoustic Guitar");
// Calling methods from interfaces and superclass
guitar.play(); // Output: Acoustic Guitar is playing
guitar.playStringSound(); // Output: Guitar strums strings
guitar.playAcousticSound(); // Output: Guitar produces acoustic sound
}
}
To define inheritance in Java practical applications, let us consider a few Java inheritance examples:
Single Inheritance: You are developing a banking application. You have a base class "Account" that contains properties and methods common to all account types, such as "balance" and "deposit." Now, you create derived classes like "SavingsAccount" and "CheckingAccount" that inherit from "Account" and add specific behaviours unique to their account types.
Multiple Inheritance: You are building a gaming engine. You have classes for "Character" and "Weapon," each with their specific attributes and methods. Now, you create a "Warrior" class that inherits from both "Character" and "Weapon," giving you a character capable of wielding a weapon.
Multilevel Inheritance: Imagine a scenario where you are developing a geometry library. You have a class "Shape" that contains general properties like "area" and "perimeter." You create a "Circle" class inheriting from "Shape" to add properties specific to circles. Then, you create a "Cylinder" class that inherits from "Circle" to introduce the third dimension.
Hybrid Inheritance: In a scenario involving e-commerce, you have a class "Product" that serves as the base for all products in your online store. You also define interfaces like "Discountable" and "Shippable." Now, you create a class "Electronics" that inherits from "Product" and implements "Discountable." This class represents electronic products that can receive discounts. Additionally, you create a class "Laptop" that inherits from "Electronics" and implements "Shippable," indicating that laptops are eligible for shipping.
Related: Java Certification Courses by Top Providers
Inheritance in Java programs is a powerful and essential concept in programming, offering a means of reusing and organising code efficiently. Understanding the various types of inheritance in Java, from single and multiple to multilevel and hybrid, equips developers with the flexibility to create complex class hierarchies. By harnessing the capabilities of inheritance, Java developers can design robust and modular applications that promote code re-usability and extensibility.
In Java, inheritance is a fundamental concept that allows a class to inherit properties and behaviours from another class. It is crucial because it promotes code reuse, extensibility, and the creation of a hierarchical class structure. This means you can build new classes based on existing ones, reducing redundancy and making your code more organised.
Java supports several types of inheritance, including single, multiple (achieved through interfaces), multilevel, hierarchical, and hybrid inheritance. Each type serves a unique purpose, offering flexibility in designing class hierarchies to suit your application's needs.
Single inheritance allows a class to inherit properties and methods from a single superclass. For example, you can have a "Car" class that inherits attributes and methods from a "Vehicle" superclass. This promotes a clear and straightforward hierarchy without ambiguity.
Java does not support multiple inheritance directly, which is the ability to inherit from more than one class. To achieve similar results, Java employs interfaces, allowing a class to implement multiple interfaces. This approach prevents issues like the "diamond problem" and promotes a cleaner design.
Understanding inheritance is vital for Java developers because it enables them to design efficient, modular, and reusable code. By mastering the various types of inheritance and their applications, developers can create complex class hierarchies and build robust Java applications more effectively.
Application Date:15 October,2024 - 15 January,2025
Application Date:11 November,2024 - 08 April,2025